package com.expert.miniapp.service.impl;

import com.expert.miniapp.dao.ChatMessage;
import com.expert.miniapp.dao.ChatMessageMapper;
import com.expert.miniapp.dao.ChatSession;
import com.expert.miniapp.dao.ChatSessionMapper;
import com.expert.miniapp.dto.ChatSessionDTO;
import com.expert.miniapp.service.ChatSessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * ChatSessionServiceImpl - 会话服务实现
 *
 * @author System
 * @since 2025-10-21
 */
@Service
public class ChatSessionServiceImpl implements ChatSessionService {

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Override
    public ChatSession createSession(String userId) {
        ChatSession session = new ChatSession();
        session.setSessionId(UUID.randomUUID().toString());
        session.setUserId(userId);
        session.setStatus("ACTIVE");
        session.setCreatedAt(LocalDateTime.now());
        session.setUpdatedAt(LocalDateTime.now());

        chatSessionMapper.insert(session);

        return session;
    }

    @Override
    public List<ChatSessionDTO> getUserSessions(String userId) {
        return chatSessionMapper.findUserSessions(userId);
    }

    @Override
    public ChatSessionDTO getSessionDetail(String sessionId) {
        ChatSession session = chatSessionMapper.selectById(sessionId);
        if (session == null) {
            return null;
        }

        // 转换为DTO
        ChatSessionDTO dto = new ChatSessionDTO();
        dto.setSessionId(session.getSessionId());
        dto.setTitle(session.getTitle());
        dto.setStatus(session.getStatus());
        dto.setUpdatedAt(session.getUpdatedAt());

        // 统计消息数量
        List<ChatMessage> messages = chatMessageMapper.findSessionMessages(sessionId);
        dto.setMessageCount(messages.size());

        return dto;
    }

    @Override
    public List<ChatMessage> getSessionMessages(String sessionId) {
        return chatMessageMapper.findSessionMessages(sessionId);
    }

    @Override
    @Transactional
    public Map<String, Object> saveMessages(String sessionId, List<ChatMessage> messages) {
        // 1. 获取当前会话的最大message_order
        Integer maxOrder = chatMessageMapper.getMaxMessageOrder(sessionId);
        int nextOrder = (maxOrder == null) ? 1 : maxOrder + 1;

        // 2. 为每条消息设置message_order和其他字段
        List<Integer> messageOrders = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();

        for (ChatMessage msg : messages) {
            msg.setMessageId(UUID.randomUUID().toString());
            msg.setSessionId(sessionId);
            msg.setMessageOrder(nextOrder);
            msg.setCreatedAt(now);

            messageOrders.add(nextOrder);
            nextOrder++;
        }

        // 3. 批量插入消息
        chatMessageMapper.insertBatch(messages);

        // 4. 如果是首次保存消息，自动设置会话标题
        ChatSession session = chatSessionMapper.selectById(sessionId);
        if (session != null && (session.getTitle() == null || session.getTitle().trim().isEmpty())) {
            // 找到第一条用户消息
            for (ChatMessage msg : messages) {
                if ("user".equals(msg.getSenderType())) {
                    String content = msg.getContent();
                    String title = content.substring(0, Math.min(20, content.length()));
                    chatSessionMapper.updateTitle(sessionId, title);
                    break;
                }
            }
        }

        // 5. 返回保存结果
        Map<String, Object> result = new HashMap<>();
        result.put("savedCount", messages.size());
        result.put("messageOrders", messageOrders);

        return result;
    }

    @Override
    public boolean renameSession(String sessionId, String title) {
        int rows = chatSessionMapper.updateTitle(sessionId, title);
        return rows > 0;
    }

    @Override
    public boolean deleteSession(String sessionId) {
        int rows = chatSessionMapper.deleteById(sessionId);
        return rows > 0;
    }

    @Override
    public List<ChatSessionDTO> searchSessions(String userId, String keyword) {
        return chatSessionMapper.searchSessions(userId, keyword);
    }
}
